# 189. 轮转数组
// 给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
if (k === 0) return nums;
const n = nums.length;
const newArr = new Array(n);
for (let i = 0; i < n; ++i) {
newArr[(i + k) % n] = nums[i];
}
for (let i = 0; i < n; ++i) {
nums[i] = newArr[i];
}
console.log(nums);
};
rotate([1, 2, 3, 4, 5, 6, 7], 3); // [5,6,7,1,2,3,4] 7 4 0 5 1 6 2
// rotate([1, 2], 3); // [5,6,7,1,2,3,4]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25